import { t } from 'i18next'
import { useEffect } from 'react'
import shallow from 'zustand/shallow'
import { ListTranslator, terminalEntity } from './translator'
import { differenceBy, findIndex } from 'lodash-es'
import { Alert } from '@/components/Alert'
import { useSelectStore } from './store'
import { ListTopActionItem } from '@/components/List'
import { fetchGetSelectViewInfo, fetchStartSelectView, fetchStopAllSelectView } from '@/api/manager/select'
import { SelectInfoEntity } from '@/api/manager/select/interface'
import { useMccStore } from '../../store'
import { MtEntity } from '@/api/manager/mt'
import { DropData } from '@/api/manager/type'
import { getItemByMtKey } from '../main/table/all/utils'
import { useTableAllStore } from '../main/table/all/store'
export const useData = () => {
	const meetingMoid = useMccStore((state) => state.mccInfo.meetingMoid)
	const {
		update,
		toggleClick,
		clearPage,
		_start,
		media_mode,
		is_mcc_meeting_selectview,
		des_account_list,
		is_call_back,
		is_call_back_mt,
	} = useSelectStore(
		(state) => ({
			update: state.update,
			toggleClick: state.toggleClick,
			clearPage: state.clearPage,
			_start: state._start,
			media_mode: state.media_mode,
			is_mcc_meeting_selectview: state.is_mcc_meeting_selectview,
			des_account_list: state.des_account_list,
			is_call_back: state.is_call_back,
			is_call_back_mt: state.is_call_back_mt,
		}),
		shallow
	)
	const topActions: ListTopActionItem[] = [
		{
			text: t('清空'),
			onClick: async () => {
				const success = await fetchStopAllSelectView(meetingMoid)
				!success && Alert(t('取消所有选看失败'))
				success && clearPage()
			},
		},
	]
	/**初始化加载数据*/
	useEffect(() => {
		loadSelectView()
	}, [is_mcc_meeting_selectview])
	/**请求选看数据*/
	const loadSelectView = async (callBack?: () => void) => {
		let res = await fetchGetSelectViewInfo(meetingMoid)
		if (res.success) {
			if (!res.data) return
			showSelectView(res.data)
			callBack && callBack()
		} else {
			Alert(t('获取终端选看失败'))
		}
	}
	/**处理选看数据*/
	const showSelectView = (select_view_data: Array<SelectInfoEntity>) => {
		if (select_view_data.length !== 0) {
			let _des_account_list = [] /**选看终端列表 */
			for (let i = 0; i < select_view_data.length; i++) {
				let current = select_view_data[i]
				if (current.des_account) {
					_des_account_list.push(current.des_account)
				}
			}
			/** 左侧添加*/
			if (
				is_call_back &&
				is_call_back_mt.length > 0 &&
				_des_account_list.findIndex((item) => item.mt_key === is_call_back_mt[0]?.mt_key) < 0
			) {
				_des_account_list.push(is_call_back_mt[0])
				update({
					des_account_list: ListTranslator(_des_account_list) /**选看终端列表 */,
					dataBackups: select_view_data /**备份数据 */,
					is_call_back: false,
					is_call_back_mt: [],
				})
				toggleClick(is_call_back_mt[0].mt_key)
			} else {
				update({
					des_account_list: ListTranslator(_des_account_list) /**选看终端列表 */,
					dataBackups: select_view_data /**备份数据 */,
				})
				toggleClick(_des_account_list[0].mt_key)
			}
		} else {
			clearPage()
			if (is_call_back) {
				update({
					des_account_list: ListTranslator(is_call_back_mt) /**选看终端列表 */,
					is_call_back: false,
					is_call_back_mt: [],
				})
				toggleClick(is_call_back_mt[0].mt_key) /**选中第一条终端 */
			}
		}
	}
	//拖拽选看终端
	const handleDropDes = (dataTransfer: DropData, index: number) => {
		if (dataTransfer && dataTransfer.data && dataTransfer.data.mt) {
			/**终端 */
			let mt = dataTransfer.data.mt
			let isMT = mt.isMt
			let conf_level = mt.conf_level
			if ((isMT || (!isMT && mt.online)) && dataTransfer.from !== 'select_view') {
				if (isMT) {
					if (conf_level !== 2) {
						Alert(t('非本级会议终端不能选看'))
						return false
					}
				} else {
					Alert(t('只能选看终端'))
					return false
				}
			}
			const flag = des_account_list.findIndex((item) => item.mtKey === mt.mt_key)
			flag === -1 && update({ src_account_list: [], _start: mt.mt_key })
			dealDrop({
				mts: ListTranslator([mt as MtEntity]),
				from: dataTransfer.from,
				dropIndex: index,
			})
			//被选看终端只能是1个 选看终端和被选看终端不能相同 被选看拖动时，选看终端必须是选中状态
		}
	}
	const handleStartSelect = async (mt_id: string) => {
		const params = {
			dst_account: _start,
			src_account: mt_id,
			flag: 0,
			media_mode: media_mode,
		}
		const res = await fetchStartSelectView(meetingMoid, params)
		if (!res.success) {
			/**
			 * (1)清空被选看列表
			 * (2)选中开始选看的被选看看终端
			 * */
			update({
				src_account_list: [],
			})
			toggleClick(_start)
			if (res.error_code === 20435) {
				let tree = useTableAllStore.getState().tree
				let src_account = getItemByMtKey(tree, mt_id)?.mcc
				let dst_account = getItemByMtKey(tree, _start || '')?.mcc
				let arr = []
				let text_src = src_account && !src_account?.status.isOnline ? src_account.name : ''
				let text_dst = dst_account && !dst_account?.status.isOnline ? dst_account.name : ''
				arr.push(text_src, text_dst)
				let _arr = arr.filter((item) => item)
				Alert(t('您指定的{{name}}不在您的会议中(20435)', { name: _arr.join(',') }))
			} else {
				Alert(res.description || t('选看失败'))
			}
		}
	}
	//拖拽被选看终端
	const handleDropSrc = (dataTransfer: DropData, index: number) => {
		if (dataTransfer && dataTransfer.data && dataTransfer.data.mt) {
			let mt = dataTransfer.data.mt
			if (!_start || _start === mt.mt_key) {
				/**
				 * (1)选看终端不存在
				 * (2)如果被选看的终端和选看的终端一致
				 */
				return false
			}
			if ((mt.isMt || mt.conf_level === 1 || (!mt.isMt && mt.online)) && dataTransfer.from !== 'select_view') {
				if (!mt.isMt && (mt.conf_level === 1 || mt.conf_level === 2)) {
					Alert(t('本级和上级会议不能被选看'))
					return false
				}
			}
			handleStartSelect(mt.mt_key)
			/**更新终端*/
			if (dataTransfer.from !== 'select_view') {
				update({ src_account_list: ListTranslator([mt as MtEntity]) || [] /**被选看终端 */ })
			}
		}
	}
	//拖拽进入列表
	const dealDrop = ({ mts, from, dropIndex }: terminalEntity) => {
		const list = des_account_list
		if (from !== 'select_view') {
			const insertList = differenceBy(mts, list, (x) => x.mtKey)
			let newList = [...list.slice(0, dropIndex), ...insertList, ...list.slice(dropIndex)]
			update({ des_account_list: newList })
			toggleClick(mts[0].mtKey)
		} else {
			const baseList = differenceBy(list, mts, (x) => x.mtKey)
			let insertToBaseIndex = dropIndex
			const baseListMtKeys = baseList.map((l) => l.mtKey)
			const nextFirstBaseListIndex = findIndex(list, (l) => baseListMtKeys.includes(l.mtKey), dropIndex)
			if (nextFirstBaseListIndex === -1) {
				insertToBaseIndex = baseList.length
			} else {
				insertToBaseIndex = baseList.findIndex((l) => l.mtKey === list[nextFirstBaseListIndex].mtKey)
			}
			update({
				des_account_list: [
					...baseList.slice(0, insertToBaseIndex),
					...mts,
					...baseList.slice(insertToBaseIndex),
				],
			})
			toggleClick(mts[0].mtKey)
		}
	}
	/**返回操作*/
	const handleReturnBack = () => {
		useMccStore.getState().setCurPage('mcc_main')
	}
	return {
		handleDropDes,
		handleDropSrc,
		/**返回操作设置主页 */
		handleReturnBack,
		/**操作按钮*/
		topActions,
	}
}
